const jwt = require('jsonwebtoken');
const jwtConfig = require('../config/jwt');
const User = require('../models/User');
const bcrypt = require('bcryptjs');

module.exports = {
  // 用户注册
  register: async (req, res) => {
    try {
      const { phone_number, password, id_card } = req.body;

      // 检查用户名是否已存在
      const existingUser = await User.findOne({ where: { phone_number },attributes: ['id'] });
      if (existingUser) {
        return res.status(400).json({
          success: false,
          message: '该手机号已注册'
        });
      }

      // 创建用户
      const user = await User.create({ phone_number, password, id_card, base_type: "本部公司" });
      // 生成Token
      const accessToken = jwt.sign(
        { userId: user.id },
        jwtConfig.secret,
        { expiresIn: jwtConfig.accessExpire, issuer: jwtConfig.issuer }
      );

      const refreshToken = jwt.sign(
        { userId: user.id, tokenVersion: user.tokenVersion },
        jwtConfig.secret,
        { expiresIn: jwtConfig.refreshExpire, issuer: jwtConfig.issuer }
      );

      res.json({
        success: true,
        code:0,
        data: {
          user: {
            id: user.id,
            phone_number: user.phone_number,
            real_name: user.real_name,
            base_type: user.base_type
          },
          accessToken,
          refreshToken
        }
      });
    } catch (err) {
      console.error('注册错误:', err);
      res.status(500).json({
        success: false,
        message: '注册失败',
        error: process.env.NODE_ENV === 'development' ? err.message : undefined
      });
    }
  },

  // 用户登录
  login: async (req, res) => {
    try {
      const { phone_number, password } = req.body;
      // 查找用户
      let user
      try {
        user = await User.findOne({ where: { phone_number } });
      } catch (err) {
        console.error('查询出错:', err);
      }
      if (!user) {
        return res.status(401).json({
          success: false,
          message: '用户不存在或密码错误' // 模糊提示防止枚举攻击
        });
      }

      // 验证密码
      try {
        const isValid = await bcrypt.compare(password.trim(), user.password);

        if (!isValid) {
          return res.status(401).json({
            success: false,
            message: '用户不存在或密码错误'
          });
        }

      } catch (err) {
        return res.status(500).json({ message: 'Authentication error' });
      }

      // 生成Token
      const accessToken = jwt.sign(
        { userId: user.id },
        jwtConfig.secret,
        { expiresIn: jwtConfig.accessExpire, issuer: jwtConfig.issuer }
      );

      const refreshToken = jwt.sign(
        { userId: user.id, tokenVersion: user.tokenVersion },
        jwtConfig.secret,
        { expiresIn: jwtConfig.refreshExpire, issuer: jwtConfig.issuer }
      );

      res.json({
        success: true,
        code: 0,
        data: {
          user: {
            id: user.id,
            phone_number: user.phone_number,
            real_name: user.real_name,
            base_type: user.base_type
          },
          accessToken,
          refreshToken
        }
      });
    } catch (err) {
      console.error('登录错误:', err);
      res.status(500).json({
        success: false,
        message: '登录失败',
        error: process.env.NODE_ENV === 'development' ? err.message : undefined
      });
    }
  },

  // 刷新Access Token
  refreshToken: async (req, res) => {
    try {
      const user = req.user;

      const accessToken = jwt.sign(
        { userId: user.id },
        jwtConfig.secret,
        { expiresIn: jwtConfig.accessExpire, issuer: jwtConfig.issuer }
      );

      res.json({ accessToken });
    } catch (err) {
      res.status(500).json({ message: err.message });
    }
  },

  // 获取当前用户信息
  me: async (req, res) => {
    try {
      const user = req.user;
      res.json({
        code: 0,
        data: {
          id: user.id,
          username: user.username,
          email: user.email,
          avatar: user.avatar
        }
      });
    } catch (err) {
      res.status(500).json({ message: err.message });
    }
  },
  roleMenu: async (req, res) => {
    const adminList = [
      {
        path: '/homepage',
        component: '#',
        name: 'HomePage',
        meta: {
          title: '主页'
        },
        redirect: '/homepage/main',
        children: [
          {
            path: 'main',
            name: 'main',
            component: 'views/Level/homePage/home',
            meta: {
              title: '主页',
              icon: 'material-symbols:add-home-work-outline'
            }
          }
        ]
      },
      {
        path: '/level',
        component: '#',
        name: 'Level',
        meta: {
          title: 'router.level',
          icon: 'carbon:skill-level-advanced'
        },
        children: [
          {
            path: 'menu1',
            name: 'Menu1',
            component: '##',
            meta: {
              title: 'router.menu1'
            },
            children: [
              {
                path: 'menu1-1',
                name: 'Menu11',
                component: 'views/Level/Menu111',
                meta: {
                  title: 'router.menu11'
                }
              },
              {
                path: 'menu1-2',
                name: 'Menu12',
                component: 'views/Level/Menu12',
                meta: {
                  title: 'router.menu12'
                }
              }
            ]
          },
          {
            path: 'menu2',
            name: 'Menu2Demo',
            component: 'views/Level/Menu2',
            meta: {
              title: 'router.menu2'
            }
          }
        ]
      }
    ]
    try {
      const user = req.user;
      res.json({
        code: 0,
        data: adminList
      });
    } catch (err) {
      res.status(500).json({ message: err.message });
    }
  }
};